const Actions = require('./actions');
const DB = require('app/db.js');
import { guid, getTime, getMarkdownText, sendNotice } from 'clientConfig/util/queryurlfield';
const monStorage = require('clientConfig/util/StoreData').monStorage;
const Storage = require('clientConfig/util/StoreData').Storage;
import { Control } from 'react-keeper';
const { Toast } = SaltUI;
import { NEW, RUNNING, TERMINATED, COMPLETED, CANCELED } from 'clientConfig/constants'

let form_component_values = null
module.exports = Reflux.createStore({
    listenables: [Actions],
    data: {

    },
    onFetch: function (params, cb) {
        let t = this;
        DB.Approval.get_approval_list({
            proj_category: "payplan",
            status: '8',
            PageNum: 0,
            CountForAPage: 100,
            id: Storage.get('user.id')
        }).then((content) => {// 成功
            var payProportionAll = [];
            var paypointeAll = [];
            var payMoneyAll = [];
            var payTotalMoneyAll = [];
            var proNameAll = [];
            var proNumAll = [];
            var process_id = [];
            var folderId = [];
            var webhookAll = [];
            var paymanage_proportion = null;
            content.list.map((item, index) => {
                var payProportionarr = [];
                var paypointeArr = [];
                var payMoney = [];
                proNameAll.push({ value: index, text: item["proj_name"] })
                item.paymanage_node.split("，").map((item, index) => {
                    paypointeArr.push({ value: index, text: item })
                })
                try {
                    paymanage_proportion = JSON.parse(item.paymanage_proportion)
                } catch (e) {
                    paymanage_proportion = item.paymanage_proportion
                }
                paymanage_proportion.proportion && paymanage_proportion.proportion.split("，").map((item, index) => {
                    payProportionarr.push(item)
                })
                paymanage_proportion.payMoney && paymanage_proportion.payMoney.split("，").map((item, index) => {
                    payMoney.push(item)
                })
                paypointeAll.push(paypointeArr);
                payProportionAll.push(payProportionarr);
                payMoneyAll.push(payMoney);
                payTotalMoneyAll.push(paymanage_proportion['payTotalMoney']);
                process_id.push(item.process_id);
                proNumAll.push(item["proj_num"]);
                folderId.push(item["folder_id"]);
                webhookAll.push(item.proj_webhook);
            })
            t.data.payProportionAll = payProportionAll;
            t.data.payMoneyAll = payMoneyAll;
            t.data.payTotalMoneyAll = payTotalMoneyAll;
            t.data.paypointeAll = paypointeAll;
            t.data.proNameAll = proNameAll;
            t.data.proNumAll = proNumAll;
            t.data.process_id = process_id;
            t.data.folderId = folderId;
            t.data.webhookAll = webhookAll;
            t.updateComponent();
        }).catch((error) => { // 失败 or 有异常被捕获

        });
    },
    onCheck: function (params, pointer) {//判断支付节点的支付申请是否提交,提交过支付申请的支付节点不在显示
        let t = this;
        DB.Approval.get_approval_list({
            proj_category: "payreq",
            proj_name: params,
            PageNum: 0,
            CountForAPage: 10
        }).then((content) => {
            debugger
            var paymanage_nodeAll = []
            if (content.list instanceof Array) {
                content.list.map((item, index) => {
                    if (item.status != TERMINATED && item.status != CANCELED) //判断不是拒绝或者撤销的支付请求不计入支付节点计算
                        paymanage_nodeAll.push(item.paymanage_node);
                })
            } else {
                if (item.status != TERMINATED && item.status != CANCELED)
                    paymanage_nodeAll.push(content.list.paymanage_node);
            }
            t.data.paymanage_nodeAll = paymanage_nodeAll;
            for (var i = 0; i < t.data.paymanage_nodeAll.length; i++) {
                for (var j = 0; j < pointer.length; j++) {
                    if (pointer[j].text == t.data.paymanage_nodeAll[i]) {
                        pointer.splice(j, 1);
                    }
                }
            }
            if (pointer.length == 0) {
                Toast.show({
                    type: 'error',
                    content: "该项目的所有支付节点的支付申请都已提交",
                    duration: 2888
                })
            }
            t.data.paypointeCurr = pointer
            t.updateComponent();
        })
    },
    onSendForm: function (params, contents, boo) {
        let t = this;
        let agent_id = Storage.get('user.agentid');
        let create_time = getTime();
        let finish_time = "";
        let originator_user = monStorage.get('user.nickname');
        let originator_user_id = Storage.get('user.id') //审批发起人的userid
        let dept_id = monStorage.get('user.department');
        let approvers = contents.spr;
        let approvers_id = contents.approvers_id;
        let cc_list = contents.csr;
        let cc_list_id = contents.cc_list_id
        let folder_id = contents.folder_id
        var array = [];
        if (approvers instanceof Array) {
            for (let i = 0; i < approvers.length; i++) {
                array.push(JSON.stringify({ content: "", file: "", imgae: "" }));
            }
        }
        let process_result = array.length > 1 ? array : JSON.stringify({ content: "", file: "", imgae: "" });
        let next_cursor = 0;
        const status = 1;
        const module_type = "payment";
        const proj_category = !boo ? "payreq" : "changereq";
        const proj_num = contents.proNum;
        const proj_name = params.data.payplan;
        const proj_webhook = contents.proj_webhook;
        const proj_markdown = getMarkdownText({ create_time, originator_user, approvers, proj_name, proj_num, status, title: "支付申请" })
        const process_id = guid();
        var nodelists = []
        let node_info = [];
        for (let i = 0; i < params.node.length; i++) {
            var obj = {}
            obj.name = params.node[i].label;
            obj.value = params.data[params.node[i].name];
            node_info.push(obj);
        }
        var obj = {}
        node_info.push({ name: '上传附件', value: contents.upfileName })
        obj.node_info = node_info
        Object.assign(obj, { node_name: !boo ? "payreq" : "changereq", modified: !boo ? "0" : '1', permission: "1" })
        nodelists.push(obj);
        form_component_values = {
            content: { paymanage_node: params.data.paypointer, paymanage_proportion: JSON.stringify({ payProportion: params.data.payProportion, payMoney: params.data.payMoney }), payplanId: contents.payplanId, Perdeductions: JSON.stringify({ Perdeductions: params.data.Perdeductions, deductionsMoney: params.data.deductionsMoney }) },
            nodelists: nodelists
        }
        var send = Object.assign({}, { agent_id, create_time, finish_time, originator_user, originator_user_id, dept_id, approvers, approvers_id, cc_list, cc_list_id, folder_id, process_result, next_cursor, status, module_type, proj_category, proj_num, proj_name, proj_webhook, proj_markdown, process_id, form_component_values })
        // console.log(send)
        if (params.pagedata) {
            send = this.modify(send, params);
        }
        let notice_info = {
            "process_id": process_id,
            "proj_num": proj_num,
            "proj_name": proj_name,
            "create_time": create_time,
            "status": status,
            "type": "待我审批的"
        }
        let noticed_lists = approvers_id instanceof Array ? approvers_id[next_cursor] : approvers_id;
        DB.Approval.send_approval.config.query = { robot: 1 }
        DB.Approval.send_approval(send)
            .then((content) => { // 成功
                Toast.show({
                    type: 'success',
                    content: '你的支付申请已提交'
                });
                sendNotice(noticed_lists, notice_info)
                Control.go(-1)
            })
            .catch((error) => { // 失败 or 有异常被捕获
                if (error.message) {
                    Toast.show({
                        type: 'error',
                        content: error.message
                    });
                } else {
                    Toast.show({
                        type: 'error',
                        content: '提交失败'
                    });
                }
            });
    },
    modify: function (new_data, old_data) {
        let edit = old_data.edit;
        old_data = old_data.pagedata;
        let old_change = [];//变更前字段 发送群消息
        let new_change = [];//变更后字段 发送群消息
        let form_component_values_new = new_data.form_component_values;
        let nodelists_new = form_component_values_new.nodelists;
        for (let i = 0; i < nodelists_new.length; i++) {
            let node_info_new = nodelists_new[i].node_info;
            let node_info_old = old_data.node_info;
            for (let j = 0; j < node_info_new.length; j++) {
                if (node_info_new[j].value != node_info_old[j].value) {
                    node_info_new[j].ext_value = node_info_old[j].value//变更过
                    old_change.push(node_info_old[j].value);
                    new_change.push(node_info_new[j].value);
                }
            }
        }
        form_component_values_new.nodelists = nodelists_new;
        form_component_values_new.content.changerecord_type = JSON.stringify({
            type: edit ? "撤销申请" : "内容变更",
            old_process_id: old_data.process_id
        })
        new_data.form_component_values = form_component_values_new;
        let { create_time, originator_user, approvers, approvers_id, cc_list, cc_list_id, next_cursor, proj_name, proj_num, status } = { ...new_data };
        const proj_markdown = getMarkdownText({ old_change, new_change, change_type: edit ? "撤销申请" : "内容变更", create_time, originator_user, approvers: approvers[next_cursor], proj_name, proj_num, status, title: '支付管理' }, "change")
        new_data.proj_markdown = proj_markdown;
        return new_data;
    },
    onUpdataApproval: function (id, data) {
        var send = data ? data : { form_component_values: form_component_values }
        DB.Approval.update_approval.config.query = { process_id: id }
        DB.Approval.update_approval({
            "form_component_values": {
                "content": send
            }
        }).then((content) => {

        }).catch((error) => { // 失败 or 有异常被捕获

        });
    },

    updateComponent: function () {
        this.trigger(this.data);
    },

    getInitialState: function () {
        return this.data;
    }
});
